package cn.pconline.autoclub.service;

import java.util.ArrayList;
import java.util.List;

import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import cn.pconline.autoclub.entity.UserVoted;
import cn.pconline.autoclub.entity.Vote;
import cn.pconline.autoclub.entity.VoteDetail;
import cn.pconline.autoclub.util.DateUtils;


/**
 *
 * @author zhoutianhuai
 */
public class VoteService {

    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private GeliDao geliDao;
    private static final Logger log = LoggerFactory.getLogger(VoteService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
   
    /**
     * 投一票vote_count加1
     * @param voteId
     * @return
     */
    private long addVoteCount(Vote vote){
        long voteCount = vote.getVoteCount();
        vote.setVoteCount(voteCount+1);
        return geliDao.update(vote,"vote_count");
    }
    
    /**
     * 投一票，选项投票数+1
     * @param voteDetail
     * @return
     */
    private long addVoteDetail(VoteDetail voteDetail){
    	long count =voteDetail.getVoteCount();
    	voteDetail.setVoteCount(count+1);
    	return geliDao.update(voteDetail,"vote_count");
    }
    
    /**
     * 创建投票内容
     *
     * @param vote
     *
     */
    public long  createVote(Vote vote) {
        return geliDao.create(vote);
    }
    
    /**
     * 创建投票主题（包括投票主题，投票选项）
     * @param vote	投票主题
     * @param details	投票选项
     * @return
     */
    public boolean createVote(Vote vote,List<VoteDetail> details){
 	   boolean flag = false;
 	   try {
 		   long voteId = createVote(vote);
 		   batchCreateVoteDetail(voteId,details);
 		   flag = true;
 	   }catch( Exception e ) {
 		   log.error("create vote throw Exception:", e);
 		   flag = false;
 	    }
 	   return flag;
    }
    
    /**
     * 用户投票
     * @param vote	投票的主题
     * @param voteDetail	投票的选项
     * @param userId	用户id
     * @return
     */
    public long createUserVoted(Vote vote,VoteDetail voteDetail,long userId){
 	   UserVoted userVoted = new UserVoted();
 	   userVoted.setUserId( userId );
 	   userVoted.setVoteId( vote.getVoteId());
 	   userVoted.setVoteItemId(voteDetail.getVoteItemId());
 	   userVoted.setCreateAt(DateUtils.getNow());
 	   long id =geliDao.create(userVoted);
 	   addVoteCount(vote);
 	   addVoteDetail(voteDetail);
 	   return id;
    }
     
    /**
     * 更新投票内容
     *
     * @param vote
     */
    public long updateVote(Vote vote) {
        return geliDao.update(vote);
    }
    
    /**
     * 创建投票选项
     * @param voteId
     * @param details
     * @return
     */
   private int batchCreateVoteDetail(long voteId,List<VoteDetail> details){
	   if( details == null || details.isEmpty()){
           return 0;
       }
	   SqlBuilder sqlBuilder = new SqlBuilder();
	   sqlBuilder.appendSql(" insert into ").appendSql(geliOrm.getTableName(VoteDetail.class));
	   sqlBuilder.appendSql(" (vote_item_id,vote_id,content) value(?,?,?) ");
	   List<Object[]> batch = new ArrayList<Object[]>();
	   for(VoteDetail detail:details) {
		   Object[] values = new Object[]{geliDao.generateId(VoteDetail.class),voteId,detail.getContent()};
		   batch.add(values);
	   }
	   return jdbcTemplate.batchUpdate(sqlBuilder.getSql(),batch).length;
   }

    /**
     * 根据voteId查找vote
     * @param voteId
     * @return
     */
    public Vote findVoteByVoteId(long voteId){
        try {
             return geliDao.find(Vote.class, voteId);
        } catch (EmptyResultDataAccessException e) {
                return null;
        }
    }
    
    /**
     * 获取未删除的投票
     * @param voteId
     * @return
     */
    public Vote getValidVote(long voteId){
    	if(voteId<1){
    		return null;
    	}
    	Vote vote = findVoteByVoteId(voteId);
    	if(vote != null && vote.getStatus() == Vote.STATUS_NORMAL){
    		return vote;
    	}
    	return null;
    }
    
    /**
     * 根据voteItemId查找voteDetail
     * @param voteId
     * @return
     */
    public VoteDetail findVoteDetailByVoteItemId(long voteItemId){
        try {
             return geliDao.find(VoteDetail.class, voteItemId);
        } catch (EmptyResultDataAccessException e) {
                return null;
        }
    }
    
    /**
     * 根据用户id，投票主题id查找用户投票记录
     * @param voteId
     * @param userId
     * @return
     */
    public UserVoted findVoteByUserId(long voteId,long userId){
    	SqlBuilder sqlBuilder = new SqlBuilder();
    	sqlBuilder.appendSql("select user_id,vote_item_id from ");
    	sqlBuilder.appendSql(geliOrm.getTableName(UserVoted.class));
    	sqlBuilder.appendSql(" where vote_id = ").appendValue(voteId);
    	sqlBuilder.appendSql(" and user_id = ").appendValue(userId);
    	try {
    		List<UserVoted> list = geliDao.list(UserVoted.class, sqlBuilder.getSql(), sqlBuilder.getValues());
    		return list!=null && list.size()>0 ? list.get(0) : null;
        }
        catch( EmptyResultDataAccessException e ) {
        	return null;
        }
    }
    
    /**
     * 根据投票主题id 查找投票选项
     * @param voteId
     * @return
     */
    public List<VoteDetail> listDetailsByVoteId(long voteId){
    	SqlBuilder sqlBuilder = new SqlBuilder();
    	sqlBuilder.appendSql(" select vote_item_id,vote_id from ");
    	sqlBuilder.appendSql(geliOrm.getTableName(VoteDetail.class));
    	sqlBuilder.appendSql(" where vote_id = ").appendValue(voteId);
    	List<VoteDetail> list = new ArrayList<VoteDetail>();
    	try {
    		list =geliDao.list(VoteDetail.class, sqlBuilder.getSql(), sqlBuilder.getValues());
        }
        catch(EmptyResultDataAccessException e ) {
        }
        return list;
    	
    }
    
   
   /**
    * 根据voteId删除投票
    * @param voteId
    * @return
    */
   public int deleteVote(long voteId){
	   Vote vote = geliDao.find(Vote.class, voteId);
	   if(vote == null){
		   return 0;
	   }
	   vote.setStatus(Vote.STATUS_DELETE);
	   return geliDao.update(vote, "status");
   }
 
}
